package com.wave.gate.netty;

import com.norco.API.NorcoAPI;
import com.norco.API.util.ByteUtil;
import com.wave.gate.dto.FaceMessage;
import com.wave.gate.dto.FaceOperation;
import com.wave.gate.mqtt.client.MqttSendClient;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.io.IOException;

@Slf4j
public class NettyServer {
    public static void main(String[] args) throws IOException, InterruptedException {
        startFaceServer(null, null);
    }

    public static void startFaceServer(MqttSendClient mqttSendClient, ThreadPoolTaskExecutor threadPoolTaskExecutor) {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup) //
                    .channel(NioServerSocketChannel.class) //
                    .option(ChannelOption.SO_BACKLOG, 128) // 设置线程队列，得到连接个数
                    .childOption(ChannelOption.SO_KEEPALIVE, true) // 设置保持活动连接状态
                    .childHandler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) {
                            ch.pipeline().addLast(new FaceDecoder());
                            ch.pipeline().addLast(new FaceEncoder());
                            ch.pipeline().addLast(new FaceServerHandler(mqttSendClient, threadPoolTaskExecutor));
                        }
                    });
            ChannelFuture cf = serverBootstrap.bind(4000).sync();
            log.info("netty监听人脸机服务器启动成功...");
            cf.channel().closeFuture().sync(); // 对关闭通道进行见监听
        } catch (InterruptedException e) {
            log.info("netty监听人脸机服务器失败，error：{}", e.getMessage());
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }


}
